//
//  GSDKUserViewController.m
//  GameSDK
//
//  Created by Johnny on 2017/8/2.
//  Copyright © 2017年 Johnny. All rights reserved.
//

#import "GSDKUserViewController.h"
#import "Masonry.h"
#import "GSDKCommonMethod.h"
#import "UIViewController+Extension.h"
#import "GSDKUserLoginView.h"
#import "GSDKUserDataController.h"
#import "GSDKUserEmailRegisteredView.h"
#import "GSDKUserNameRegisteredView.h"
#import "YYKit.h"
#import "GSDKResponseModel.h"
#import "GSDKUserAccountView.h"
#import "GSDKActivityIndicatorView.h"
#import "GSDKMessagePopView.h"
#import "GSDKUserForgotPasswordView.h"
#import "GSDKComplatformBase.h"
#import "GSDKWebViewController.h"
#import "GSDKUserSwitchAccuntView.h"
#import "UIAlertView+Extension.h"

#import "GSDKRequestModel.h"
@interface GSDKUserViewController () 
@property (nonatomic, strong) GSDKUserDataController * thirdPartyDC;
@property (nonatomic, strong) UIButton * backgroundButton;
@property (nonatomic, strong) UIView * moveView;
@property (nonatomic, strong) GSDKUserAccountView * accountView;
@property (nonatomic, strong) GSDKUserLoginView * loginView;
@property (nonatomic, strong) GSDKUserEmailRegisteredView * emailRegisteredView;
@property (nonatomic, strong) GSDKUserNameRegisteredView * nameRegisteredView;
@property (nonatomic, strong) GSDKUserForgotPasswordView * forgotPasswordView;
@property (nonatomic, strong) GSDKUserSwitchAccuntView * switchAccuntView;
@end

@implementation GSDKUserViewController

- (void)dealloc {
    DEBUGMSG(@"GSDKUserViewController dealloc");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasHiden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(cancel)
                                                 name:GSDKUserCancelNoticationName object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

+ (GSDKUserViewController *)show {
    GSDKUserViewController * vc = [[GSDKUserViewController alloc] init];
    [[UIViewController getCurrentRootViewController].view addSubview:vc.view];
    [vc.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.mas_equalTo(0);
    }];
    
    return vc;
}

#pragma mark - Init View
- (void)setupUI {
    _backgroundButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _backgroundButton.backgroundColor = [UIColor blackColor];
    _backgroundButton.alpha = 0.3;
    [_backgroundButton addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_backgroundButton];
    
    [_backgroundButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(@([GSDKCommonMethod getHight]*3));
        make.center.equalTo(@0);
    }];
}

#pragma mark --- 自动布局
- (void)defaultLayoutUI:(UIView *)view height:(CGFloat)height {
    [view mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.width.mas_equalTo(UserViewWidth);
        make.height.mas_equalTo(height == 0 ? UserViewHeight : height);
        make.centerX.mas_equalTo([GSDKCommonMethod getWidth]*2);
    }];
}

- (void)centerLayoutUI:(UIView *)view {
    [view mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
    }];
}

- (void)removeLayoutUI:(UIView *)view {
    [view mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@(-[GSDKCommonMethod getWidth]*2));
    }];
}

#pragma mark 移动视图
- (void)animationComeAt:(UIView*)view {
    view.alpha = 1;
    _moveView = view;
    __weak GSDKUserViewController* bSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [bSelf centerLayoutUI:view];
        [UIView animateWithDuration:0.25 animations:^{
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {}];
    });
}

- (void)animationBackAt:(UIView*)view {
    [self.view endEditing:true];
    __weak GSDKUserViewController* bSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [bSelf removeLayoutUI:view];
        [UIView animateWithDuration:0.25 animations:^{
            [self.view layoutIfNeeded];
            view.alpha = 0;
        } completion:^(BOOL finished) {
        }];
    });
}

#pragma mark 账户界面
- (void)setupAccountView:(BOOL)isDefualt {
    BOOL isReload = NO;
    if (!_accountView) {
        _accountView = [[GSDKUserAccountView alloc]init];
        [self.view addSubview:_accountView];
        isReload = YES;
    }
    [self defaultLayoutUI:_accountView height: 250];
    [self animationComeAt:_accountView];
    
    @weakify(self)
    if (isDefualt || isReload) {
        if (GSDKCOMMONMETHOD.accountModel != nil) {
            GSDKUserAccountViewModel * viewModel = [GSDKUserAccountViewModel new];
            viewModel.userName = GSDKCOMMONMETHOD.accountModel.userName;
            [self.accountView reloadAt:viewModel];
        } else {
            [[GSDKUserDataController new] getDefaultUserAt:^(GSDKUserAccountModel *userAccount) {
                @strongify(self)
                [self.view endEditing:true];
                [[GSDKActivityIndicatorView shared] show];
                
                [[GSDKUserDataController new] loginWithUsername:userAccount.userName withPassword:userAccount.passWord withToken:GSDKCOMMONMETHOD.GSDKToken withType:(ThirdPartyLoginType)userAccount.type withOther:userAccount.other withCompletionBlock:^(id responseObject) {
                    @strongify(self)
                    [[GSDKActivityIndicatorView shared] hide];
                    GSDKUserAccountViewModel * viewModel = [GSDKUserAccountViewModel new];
                    viewModel.userName = userAccount.userName;
                    [self.accountView reloadAt:viewModel];
                } withFailureBlock:^(NSString *msg) {
                    @strongify(self)
                    [[GSDKActivityIndicatorView shared] hide];
                    [self animationBackAt:self.accountView];
                    [self setupLoginView:true];
                }];
            }];
        }
    }
    
    _accountView.comeBlock = ^{
        @strongify(self)
        [self cancel];
    };
    
    _accountView.centerBlock = ^{
        GSDKWebViewController * vc = [GSDKWebViewController new];
        GSDKWebModel * wModel = [[GSDKWebModel alloc] initIAPCallBackWithSid:GSDKCOMMONMETHOD.GSDKSid == nil ? GSDKCOMMONMETHOD.GSDKSid : @"" andToken:GSDKCOMMONMETHOD.GSDKToken andLogin_token: GSDKCOMMONMETHOD.accountModel.token];
        NSString * urlString = @"http://wap.zy1game.com";
        if (![urlString hasSuffix:@"?"]) { urlString = [NSString stringWithFormat:@"%@?", urlString]; }
        [vc reloadAtUrl: [NSString stringWithFormat:@"%@%@", urlString, [wModel getUrlParameter]]];
        [[UIViewController getCurrentRootViewController] presentViewController:vc animated:true completion:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:GSDKToolBarDidFinishNotification object:@YES userInfo:nil];
    };
    
    _accountView.switchAccountBlock = ^{
        @strongify(self)
        [self animationBackAt:self.accountView];
        [self setupSwtichAccountView];
    };
    
    _accountView.registeredBlock = ^{
        @strongify(self)
        [self animationBackAt:self.accountView];
        [self setupEmailRegisteredView];
    };
}

#pragma mark 切换账号
- (void)setupSwtichAccountView {
    if (!_switchAccuntView) {
        _switchAccuntView = [[GSDKUserSwitchAccuntView alloc]init];
        [self.view addSubview:_switchAccuntView];
    }
    [self defaultLayoutUI:_switchAccuntView height: 260];
    [self animationComeAt:_switchAccuntView];
    
    @weakify(self)
    _switchAccuntView.backBlock = ^{
        @strongify(self)
        [self animationBackAt:self.switchAccuntView];
        [self setupAccountView:false];
    };
    
    _switchAccuntView.loginBlock = ^{
        @strongify(self)
        [self animationBackAt:self.switchAccuntView];
        [self setupLoginView:true];
    };
    
    _switchAccuntView.signupBlock = ^{
        @strongify(self)
        [self animationBackAt:self.switchAccuntView];
        [self setupEmailRegisteredView];
    };
    
    _switchAccuntView.fastSignupBlock = ^{
        @strongify(self)
        [[GSDKActivityIndicatorView shared] show];
        [[GSDKUserDataController new] getNameWithToken:GSDKCOMMONMETHOD.GSDKToken withCompletionBlock:^(id responseObject) {
            if ([responseObject isKindOfClass:[GSDKResGetnameModel class]]) {
                GSDKResGetnameModel * model = (GSDKResGetnameModel *)responseObject;
                [self.view endEditing:true];
                [[GSDKUserDataController new] registeredWithUsername:model.user_name withPassword:model.password withToken:GSDKCOMMONMETHOD.GSDKToken withType:ThirdPartyLoginTypeName withSaveAlbum:true withCompletionBlock:^(id responseObject) {
                    @strongify(self)
                    [[GSDKActivityIndicatorView shared] hide];
                    [self cancel];
                } withFailureBlock:^(NSString *msg) {
                    [[GSDKActivityIndicatorView shared] hide];
                    [UIAlertView showAt:msg];
                }];
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[GSDKActivityIndicatorView shared] hide];
                    [UIAlertView showAt:[NSString localizedStringForKey:@"GSDK_server_error" value:@"服务器错误"]];
                });
            }
        } withFailureBlock:^(NSString *msg) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[GSDKActivityIndicatorView shared] hide];
                [UIAlertView showAt:msg];
            });
        }];
    };
    
    _switchAccuntView.thirdPartyBlock = ^(ThirdPartyLoginType type) {
        @strongify(self)
        if (self.thirdPartyDC == nil) {
            self.thirdPartyDC = [[GSDKUserDataController alloc] init];
        }
        [[GSDKActivityIndicatorView shared] show];
        [self.thirdPartyDC thirdPartyLogin:type withCompletionBlock:^(id responseObject) {
            [[GSDKUserDataController new] loginWithUsername:@"" withPassword:@"" withToken:GSDKCOMMONMETHOD.GSDKToken withType:type withOther:[responseObject modelToJSONString] withCompletionBlock:^(id responseObject) {
                @strongify(self)
                [[GSDKActivityIndicatorView shared] hide];
                [self cancel];
            } withFailureBlock:^(NSString *msg) {
                [[GSDKActivityIndicatorView shared] hide];
                [UIAlertView showAt:msg];
            }];
        } withFailureBlock:^(NSString *msg) {
            [[GSDKActivityIndicatorView shared] hide];
            [UIAlertView showAt:msg];
        }];
    };
}

#pragma mark 登录
- (void)setupLoginView:(BOOL)defaultAccount {
    BOOL isInit = NO;
    if (!_loginView) {
        isInit = YES;
        self.loginView = [[GSDKUserLoginView alloc] init];
        [self.view addSubview:_loginView];
    }
    [self defaultLayoutUI:_loginView height:240];
    [self animationComeAt:_loginView];
    
    @weakify(self)
    if (defaultAccount || isInit) {
        //获取默认信息
        [[GSDKUserDataController new] getAccountUserAt:^(GSDKUserAccountModel *userAccount) {
            @strongify(self)
            if (userAccount != nil) {
                GSDKUserLoginViewModel * loginViewModel = [[GSDKUserLoginViewModel alloc] init];
                loginViewModel.userName = userAccount.userName;
                loginViewModel.passWord = userAccount.passWord;
                loginViewModel.userHistorys = [[[GSDKUserDataController alloc] init] getAllAccounds];
                [self.loginView reloadAt:loginViewModel];
            }
        }];
    }
    
    _loginView.backBlock = ^{
        @strongify(self)
        [self animationBackAt:self.loginView];
        [self setupSwtichAccountView];
    };
    
    _loginView.loginBlock = ^(NSString *unString, NSString *pwString, BOOL isMore) {
        @strongify(self)
        [self.view endEditing:true];
        [[GSDKActivityIndicatorView shared] show];
        [[GSDKUserDataController new] loginWithUsername:unString withPassword:pwString withToken:GSDKCOMMONMETHOD.GSDKToken withType:ThirdPartyLoginTypeEmail withOther:@"" withCompletionBlock:^(id responseObject) {
            @strongify(self)
            [[GSDKActivityIndicatorView shared] hide];
            [self cancel];
        } withFailureBlock:^(NSString *msg) {
            @strongify(self)
            [[GSDKActivityIndicatorView shared] hide];
            GSDKUserErrorViewModel * viewModel = [[GSDKUserErrorViewModel alloc] init];
            viewModel.errorString = msg;
            [self.loginView errorAt:viewModel];
        }];
    };
    
    _loginView.forgotBlock = ^{
        @strongify(self)
        [self animationBackAt:self.loginView];
        [self setupForgotPasswordView];
    };
}

#pragma mark 用户名注册
- (void)setupNameRegisteredView {
    if (!_nameRegisteredView) {
        self.nameRegisteredView = [[GSDKUserNameRegisteredView alloc] init];
        [self.view addSubview:_nameRegisteredView];
    }
    [self defaultLayoutUI:_nameRegisteredView height:0];
    [self animationComeAt:_nameRegisteredView];
    
    GSDKUserNameRegisteredViewModel * viewModel = [GSDKUserNameRegisteredViewModel new];
    viewModel.userName = @"";
    viewModel.passWord = @"";
    [self.nameRegisteredView reloadAt:viewModel];
    
     @weakify(self)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[GSDKActivityIndicatorView shared] show];
        [[GSDKUserDataController new] getNameWithToken:GSDKCOMMONMETHOD.GSDKToken withCompletionBlock:^(id responseObject) {
            dispatch_async(dispatch_get_main_queue(), ^{
                @strongify(self)
                [[GSDKActivityIndicatorView shared] hide];
                if ([responseObject isKindOfClass:[GSDKResGetnameModel class]]) {
                    [self.nameRegisteredView reloadAt:[GSDKUserNameRegisteredViewModel getViewModel:responseObject]];
                } else {
                    GSDKUserErrorViewModel * viewModel = [[GSDKUserErrorViewModel alloc] init];
                    viewModel.errorString = [NSString localizedStringForKey:@"GSDK_server_error" value:@"服务器错误"];
                    [self.nameRegisteredView errorAt:viewModel];
                }
            });
        } withFailureBlock:^(NSString *msg) {
            dispatch_async(dispatch_get_main_queue(), ^{
                @strongify(self)
                [[GSDKActivityIndicatorView shared] hide];
                GSDKUserErrorViewModel * viewModel = [[GSDKUserErrorViewModel alloc] init];
                viewModel.errorString = msg;
                [self.nameRegisteredView errorAt:viewModel];
            });
        }];
    });
    
    _nameRegisteredView.backBlock = ^{
        @strongify(self)
        [self animationBackAt:self.nameRegisteredView];
        [self setupEmailRegisteredView];
    };
    
    _nameRegisteredView.oneSecondRegisterBlock = ^(NSString *unString, NSString *pwString) {
        @strongify(self)
        [self.view endEditing:true];
        [[GSDKActivityIndicatorView shared] show];
        [[GSDKUserDataController new] registeredWithUsername:unString withPassword:pwString withToken:GSDKCOMMONMETHOD.GSDKToken withType:ThirdPartyLoginTypeName withSaveAlbum:true withCompletionBlock:^(id responseObject) {
            @strongify(self)
            [[GSDKActivityIndicatorView shared] hide];
            [self cancel];
        } withFailureBlock:^(NSString *msg) {
            @strongify(self)
            [[GSDKActivityIndicatorView shared] hide];
            GSDKUserErrorViewModel * viewModel = [[GSDKUserErrorViewModel alloc] init];
            viewModel.errorString = msg;
            [self.nameRegisteredView errorAt:viewModel];
        }];
    };
}

#pragma mark 邮箱注册
- (void)setupEmailRegisteredView {
    if (!_emailRegisteredView) {
        self.emailRegisteredView = [[GSDKUserEmailRegisteredView alloc]init];
        [self.view addSubview:_emailRegisteredView];
    }
    [self defaultLayoutUI:_emailRegisteredView height:240];
    [self animationComeAt:_emailRegisteredView];
    
    @weakify(self)
    
    _emailRegisteredView.oneSecondRegisterBlock = ^{
        @strongify(self)
        [self animationBackAt:self.emailRegisteredView];
        [self setupNameRegisteredView];
    };
    
    _emailRegisteredView.backBlock = ^{
        @strongify(self)
        [self animationBackAt:self.emailRegisteredView];
        [self setupSwtichAccountView];
    };
    
    _emailRegisteredView.registerBlock = ^(NSString *unString, NSString *pwString) {
        @strongify(self)
        [self.view endEditing:true];
        [[GSDKActivityIndicatorView shared] show];
        [[GSDKUserDataController new] registeredWithUsername:unString withPassword:pwString withToken:GSDKCOMMONMETHOD.GSDKToken withType:ThirdPartyLoginTypeEmail withSaveAlbum:false withCompletionBlock:^(id responseObject) {
            @strongify(self)
            [[GSDKActivityIndicatorView shared] hide];
            [self cancel];
        } withFailureBlock:^(NSString *msg) {
            @strongify(self)
            [[GSDKActivityIndicatorView shared] hide];
            GSDKUserErrorViewModel * viewModel = [[GSDKUserErrorViewModel alloc] init];
            viewModel.errorString = msg;
            [self.emailRegisteredView errorAt:viewModel];
        }];
    };
}

#pragma mark 找回密码
- (void)setupForgotPasswordView {
    if (!_forgotPasswordView) {
        self.forgotPasswordView = [[GSDKUserForgotPasswordView alloc]init];
        [self.view addSubview:_forgotPasswordView];
    }
    [self defaultLayoutUI:_forgotPasswordView height:170];
    [self animationComeAt:_forgotPasswordView];
    
    @weakify(self)
    _forgotPasswordView.backBlock = ^{
        @strongify(self)
        [self animationBackAt:self.forgotPasswordView];
        [self setupLoginView:NO];
    };
    
    _forgotPasswordView.forgotPasswordBlock = ^(ForgotPasswordType type) {
        GSDKWebViewController * vc = [GSDKWebViewController new];
        GSDKWebModel * wModel = [[GSDKWebModel alloc] initIAPCallBackWithSid:GSDKCOMMONMETHOD.GSDKSid == nil ? GSDKCOMMONMETHOD.GSDKSid : @"" andToken:GSDKCOMMONMETHOD.GSDKToken andLogin_token: @""];
        NSString * urlString = @"http://wap.zy1game.com/forget_password.html";
        if (![urlString hasSuffix:@"?"]) { urlString = [NSString stringWithFormat:@"%@?", urlString]; }
        [vc reloadAtUrl: [NSString stringWithFormat:@"%@%@", urlString, [wModel getUrlParameter]]];
        [[UIViewController getCurrentRootViewController] presentViewController:vc animated:true completion:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:GSDKToolBarDidFinishNotification object:@YES userInfo:nil];
    };
}

#pragma mark - Action
- (void)clickAction {
    [self.view endEditing:true];
}

#pragma mark - NSNotification
- (void)keyboardWasShown:(NSNotification*)notification {
    float animationDuration = [[[notification userInfo] valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [_moveView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(@-80);
    }];
    __weak GSDKUserViewController* bSelf = self;
    [UIView animateWithDuration:animationDuration animations:^{
        [bSelf.view layoutIfNeeded];
    }];
}

- (void)keyboardWasHiden:(NSNotification*)notification {
    float animationDuration = [[[notification userInfo] valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [_moveView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(@0);
    }];
    __weak GSDKUserViewController* bSelf = self;
    [UIView animateWithDuration:animationDuration animations:^{
        [bSelf.view layoutIfNeeded];
    }];
}

- (void)cancel {
    if (GSDKCOMMONMETHOD.accountModel) {
        [GSDKMessagePopView showAt:[NSString stringWithFormat:@"%@, %@", GSDKCOMMONMETHOD.accountModel.userName, [NSString localizedStringForKey:@"GSDK_welcome_text" value:@"欢迎您回来"]] andBGColor:nil];
        
        GSDKAccountStatus * user = [[GSDKAccountStatus alloc] init];
        user.gSDKAccountStatus = GSDK_ACCOUNT_STATUS_MEMBER;
        GSDKMessageStatus * message = [[GSDKMessageStatus alloc] init];
        message.code = @"0";
        message.msg = [NSString localizedStringForKey:@"GSDK_loginsuccess_text" value:@"登录成功"];
        [[NSNotificationCenter defaultCenter] postNotificationName:GSDKUserDidFinishNotification object:nil userInfo:@{@"GSDKAccountStatus": user, @"GSDKMessageStatus": message}];
    }
    self.thirdPartyDC = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.view removeFromSuperview];
    _cancelBlock();
}

@end
